from tkinter.font import names

from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated, AllowAny
from .models import Route
from .serializers import RouteSerializer, RouteTreeSerializer
from ..UserManagement.models import User
from ..utils.response_utils import api_response, ResponseCode


class RouteListView(APIView):
    """
    获取当前用户类型的路由树
    """
    permission_classes = [AllowAny]

    @swagger_auto_schema(
        operation_description="获取当前用户类型的路由树",
        manual_parameters=[
            openapi.Parameter('user_type', openapi.IN_QUERY, description="用户类型", type=openapi.TYPE_INTEGER,
                              enum=[0, 1]),
        ],
        responses={200: '获取成功', 400: '获取失败，参数存在错误', 404: '路由树或用户类型不存在'},
        tags=['路由管理']
    )
    def get(self, request):
        """
        获取当前用户类型的路由树
        """
        user_type = request.query_params.get("user_type")
        if not User.objects.filter(user_type=user_type).exists():
            return api_response(ResponseCode.NOT_FOUND, "用户类型不存在")
        if not user_type:
            return api_response(ResponseCode.BAD_REQUEST, "未传入用户类型")
        routes = Route.objects.filter(user_type=user_type, parent__isnull=True).order_by('index')
        if not routes:
            return api_response(ResponseCode.NOT_FOUND, "路由树不存在")
        serializer = RouteTreeSerializer(routes, many=True)
        return api_response(ResponseCode.SUCCESS, "获取成功", serializer.data)


class CreateRouteView(APIView):
    """
    创建新的路由
    """
    permission_classes = [AllowAny]

    @swagger_auto_schema(
        operation_description="创建一个新的路由",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=['name', 'route', 'icon', 'is_leaf', 'app_url', 'parent', 'user_type', 'title'],
            properties={
                'name': openapi.Schema(type=openapi.TYPE_STRING, description="路由名称"),
                'route': openapi.Schema(type=openapi.TYPE_STRING, description="路由路径"),
                'icon': openapi.Schema(type=openapi.TYPE_STRING, description="路由图标"),
                'is_leaf': openapi.Schema(type=openapi.TYPE_BOOLEAN, description="是否有子路由，布尔值"),
                'app_url': openapi.Schema(type=openapi.TYPE_STRING, description="路由组件名称"),
                'parent': openapi.Schema(type=openapi.TYPE_STRING, description="父路由的ID"),
                'user_type': openapi.Schema(type=openapi.TYPE_INTEGER, description="用户类型（0: 普通用户, 1: 管理员）"),
                'title': openapi.Schema(type=openapi.TYPE_STRING, description="路由标题"),
            }
        ),
        responses={
            200: '创建成功',
            400: '创建失败，参数存在错误或其他错误',
            404: '参数不存在，未找到父路由或用户类型',
            409: '路由名或路由已存在',
        },
        tags=['路由管理']
    )
    def post(self, request):
        """
        创建新路由
        """
        name = request.data.get("name")
        route = request.data.get("route")
        icon = request.data.get("icon", None)
        is_leaf = request.data.get("is_leaf", False)
        app_url = request.data.get("app_url")
        parent = request.data.get("parent", None)
        user_type = request.data.get("user_type")
        title = request.data.get("title")
        if Route.objects.filter(name=name).exists():
            return api_response(ResponseCode.CONFLICT, "路由名已存在")
        if parent is not None and parent != "":
            if not Route.objects.filter(id=parent).exists():
                return api_response(ResponseCode.NOT_FOUND, "父路由不存在")
        if Route.objects.filter(route=route).exists():
            return api_response(ResponseCode.BAD_REQUEST, "路由已存在")
        if Route.objects.filter(title=title).exists():
            return api_response(ResponseCode.BAD_REQUEST, "路由标题已存在")
        if not User.objects.filter(user_type=user_type).exists():
            return api_response(ResponseCode.NOT_FOUND, "用户类型不存在")
        route_data = {
            'name': name,
            'route': route,
            'icon': icon,
            'is_leaf': is_leaf,
            'app_url': app_url,
            'parent': parent,
            'user_type': user_type,
            'title': title
        }
        serializer = RouteSerializer(data=route_data)
        if serializer.is_valid():
            serializer.save()
            return api_response(ResponseCode.SUCCESS, "添加成功")
        return api_response(ResponseCode.BAD_REQUEST, serializer.errors)


class ModifyRouteView(APIView):
    """
    更新路由
    """
    permission_classes = [AllowAny]

    @swagger_auto_schema(
        operation_description="更新指定的路由",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=['id', 'name', 'route', 'user_type'],
            properties={
                'id': openapi.Schema(type=openapi.TYPE_STRING, description="路由ID"),
                'name': openapi.Schema(type=openapi.TYPE_STRING, description="路由名称"),
                'route': openapi.Schema(type=openapi.TYPE_STRING, description="路由路径"),
                'icon': openapi.Schema(type=openapi.TYPE_STRING, description="路由图标"),
                'is_leaf': openapi.Schema(type=openapi.TYPE_BOOLEAN, description="是否有子路由"),
                'app_url': openapi.Schema(type=openapi.TYPE_STRING, description="路由组件名"),
                'parent': openapi.Schema(type=openapi.TYPE_STRING, description="父路由ID"),
                'user_type': openapi.Schema(type=openapi.TYPE_INTEGER, description="用户类型（0: 普通用户, 1: 管理员）"),
                'title': openapi.Schema(type=openapi.TYPE_STRING, description="路由标题")
            }
        ),
        responses={
            200: openapi.Response(description="更新成功"),
            400: openapi.Response(description="请求参数错误"),
            404: openapi.Response(description="未找到指定路由或父路由"),
            409: openapi.Response(description="路由名称冲突"),
        },
        tags=['路由管理']
    )
    def put(self, request):
        """
        更新路由
        """
        route_id = request.data.get("id")
        name = request.data.get("name")
        route = request.data.get("route")
        icon = request.data.get("icon", None)
        is_leaf = request.data.get("is_leaf", False)
        app_url = request.data.get("app_url")
        parent = request.data.get("parent", None)
        user_type = request.data.get("user_type")
        title = request.data.get("title")

        route_obj = Route.objects.get(id=route_id)
        if not route_obj:
            return api_response(ResponseCode.NOT_FOUND, "未找到该路由")
        if Route.objects.filter(name=name).exclude(id=route_id).exists():
            return api_response(ResponseCode.CONFLICT, "路由名已存在")
        if Route.objects.filter(route=route).exclude(id=route_id).exists():
            return api_response(ResponseCode.BAD_REQUEST, "路由已存在")
        if Route.objects.filter(title=title).exclude(id=route_id).exists():
            return api_response(ResponseCode.BAD_REQUEST, "路由标题已存在")
        if parent is not None:
            if not Route.objects.filter(id=parent).exists():
                return api_response(ResponseCode.NOT_FOUND, "父路由不存在")
        if user_type not in [0, 1]:
            return api_response(ResponseCode.BAD_REQUEST, "无效的用户类型")
        route_data = {
            'name': name,
            'route': route,
            'icon': icon,
            'is_leaf': is_leaf,
            'app_url': app_url,
            'parent': parent,
            'user_type': user_type,
            'title': title
        }
        serializer = RouteSerializer(route_obj, data=route_data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return api_response(ResponseCode.SUCCESS, "更新成功")
        return api_response(ResponseCode.BAD_REQUEST, serializer.errors)


class DeleteRouteView(APIView):
    """
    删除路由
    """
    permission_classes = [AllowAny]

    @swagger_auto_schema(
        operation_description="批量删除路由",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=['ids'],
            properties={
                'ids': openapi.Schema(
                    type=openapi.TYPE_ARRAY,
                    items=openapi.Schema(type=openapi.TYPE_STRING),
                    description="路由 ID 列表"
                )
            }
        ),
        responses={
            200: openapi.Response(description="删除成功"),
            400: openapi.Response(description="请求参数错误"),
            404: openapi.Response(description="部分或全部路由未找到"),
            500: openapi.Response(description="服务器错误"),
        },
        tags=['路由管理']
    )
    def delete(self, request):
        """
        批量删除路由
        """
        route_ids = request.data.get("ids", [])

        if not route_ids:
            return api_response(ResponseCode.BAD_REQUEST, "请求参数错误，路由 ID 列表不能为空")

        # 批量查询路由
        routes = Route.objects.filter(id__in=route_ids)

        if not routes:
            return api_response(ResponseCode.NOT_FOUND, "未找到指定的路由")

        # 删除路由
        deleted_count, _ = routes.delete()

        if deleted_count > 0:
            return api_response(ResponseCode.SUCCESS, f"成功删除 {deleted_count} 条路由")
        else:
            return api_response(ResponseCode.INTERNAL_SERVER_ERROR, "删除失败，未知错误")